/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package orgarqsindex.btree;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 *
 * @author Fernando Molon Toigo e Dyoni Bertuol
 */
public class BTreeGenerator {
    private File sourceFile;
    private int rowSize;
    private int primaryKeyBeginIndex;
    private int primaryKeySize;
    
    public BTreeGenerator(File sourceFile, int rowSize, int primaryKeyBeginIndex, int primaryKeySize){
        this.sourceFile = sourceFile;
        this.rowSize = rowSize;
        this.primaryKeyBeginIndex = primaryKeyBeginIndex;
        this.primaryKeySize = primaryKeySize;
    }
    
    public BTreeNode generate() throws FileNotFoundException, IOException{
        RandomAccessFile sraf = new RandomAccessFile(sourceFile, "r");
        
        byte[] buffer = new byte[primaryKeySize];
        BTreeNode rootNode = new BTreeNode(null);
        
        for (long i = 0; i < sourceFile.length(); i += rowSize){
            sraf.seek(i + primaryKeyBeginIndex);
            sraf.read(buffer);
            
            long key = Long.valueOf(new String(buffer, "ISO-8859-1"));
            long value = i / rowSize;
            
            rootNode.addKey(new BTreeNodeKey(key, value));
        }
        
        sraf.close();
        
        return rootNode;
    }
}
